package phone.qyg.com.qyg.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.JSONTool;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.app.view.BaseViewStateLayout;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.adapter.FindAllAdapter;
import phone.qyg.com.qyg.model.Activity;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.Course;
import phone.qyg.com.qyg.model.Find;
import phone.qyg.com.qyg.model.Venues;

/**
 * 作者：lblbh on 2017/12/5 15:18
 * 邮箱：lanbuhan@163.com
 * 功能：全局搜索结果页
 */
@ContentView(R.layout.find_end)
public class FindEndActivity extends BaseActivity {

    @ViewInject(R.id.type)
    TextView type;

    @ViewInject(R.id.quit)
    TextView quit;

    @ViewInject(R.id.find_edit)
    TextView find_edit;

    @ViewInject(R.id.linear)
    LinearLayout linear;

    BaseViewStateLayout baseView;

    RecyclerView recycler;

    Find find;

    @Override
    public void initSucessView() {
        Object obj = getTransModels();

        if(obj instanceof Find){
            find = (Find)obj;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if(find == null)return;
        type.setText(find.base.title);
        find_edit.setText(find.key);

        baseView = new BaseViewStateLayout(QXApplication.getContext()) {

            @Override
            public View obtionView() {
                View sucessView = View.inflate(QXApplication.getContext(), R.layout.base_recycler,null);
                recycler = (RecyclerView) sucessView.findViewById(R.id.recycler);
                return sucessView;
            }

            @Override
            public Object obtionData() {
                getInitNetwork();
                return DELFAUTSTATE;
            }
        };

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linear.addView(baseView,layoutParams);
        x.view().inject(linear);
    }


    /**
     * 执行网络请求
     */
    private void getInitNetwork(){

        /**
         “siteId”:1 //站点Id
         “type”：1       //检索类型：0场馆  1活动  2课程
         “content”:”赛事...”    //检索内容
         “longitude”:”116.343”,//经度（场馆）
         “latitude”:”40.33242”//纬度（场馆）
         “cityId”:1,   //当前所在城市ID（场馆）
         */

        mapKeys.put(AppHttpKey.TYPE,String.valueOf(find.base.id));
        mapKeys.put(AppHttpKey.CONTENT,find.key);

        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.GLOBAL_SEARCH,
                mapKeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);

                        //venueCount venueList courseCount courseList actCount actList

                        List<Object> temps = resultChangsList(result);

                        if(!isRequestList(temps)){
                            baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_EMPTY);
                            baseView.stateView();
                            return;
                        }
                        //成功获取到数据
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_SUCESS);
                        baseView.stateView();

                        setModelData(temps);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_ERROE);
                        baseView.stateView();
                    }
                });
    }


    private void setModelData(List<Object> models) {
        final FindAllAdapter adapter = new FindAllAdapter(QXApplication.getContext(),models);
        recycler.setAdapter(adapter);

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                SystemPrintl.systemPrintl("我在点击item-----FInd");
                Object obj = adapter.getDatas().get(position);
                if(obj instanceof Course){
                    TransformController.transformControllerModel(QXApplication.getContext(),CourseDetailActivity.class,obj);
                }else if(obj instanceof Venues){
                    TransformController.transformControllerModel(QXApplication.getContext(),VenuesDetailActivity.class,obj);
                }else if(obj instanceof Activity){
                    TransformController.transformControllerModel(QXApplication.getContext(),ActivityDetailActivity.class,obj);
                }else if((obj instanceof Base) && (((Base)obj).type == 2)){
                    Base base = (Base) obj;
                    String title = base.title;
                    Base temp = find.base;//传递Find Base
                    if(QXApplication.getContext().getString(R.string.find_end_act_more).equals(title)){
                        //活动
//                        FindEndActivity.this.finish();
                        temp.id = 1;
//                        temp.title = QXApplication.getContext().getString(R.string.find_end_act_more);
//                        TransformController.transformControllerModel(QXApplication.getContext(),
//                                    FindEndActivity.class,
//                                    find);
                        type.setText(R.string.act);
                        getInitNetwork();
                    }else if(QXApplication.getContext().getString(R.string.find_end_venue_more).equals(title)){
                        //场馆
//                        FindEndActivity.this.finish();
                        temp.id = 0;
//                        temp.title = QXApplication.getContext().getString(R.string.find_end_venue_more);
//                        TransformController.transformControllerModel(QXApplication.getContext(),
//                                FindEndActivity.class,
//                                find);
                        type.setText(R.string.venue);
                        getInitNetwork();
                    }else if(QXApplication.getContext().getString(R.string.find_end_course_more).equals(title)){
                        //课程
//                        FindEndActivity.this.finish();
                        temp.id = 2;
//                        temp.title = QXApplication.getContext().getString(R.string.find_end_course_more);
//                        TransformController.transformControllerModel(QXApplication.getContext(),
//                                FindEndActivity.class,
//                                find);
                        type.setText(R.string.course);
                        getInitNetwork();
                    }
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }


    private List<Object> resultChangsList(String result){

        List<Object> temps = new ArrayList<Object>();
        Base base = find.base;
        int typeId = base.id;

        if(typeId == 0){
            //场馆
            List<Venues> venuess = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.VENUE_LIST, Venues.class);
            if(isRequestList(venuess))
                temps.addAll(venuess);
        }else if(typeId == 1){
            //活动
            List<Activity> acts = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.ACT_LIST, Activity.class);
            if(isRequestList(acts))
                temps.addAll(acts);
        }else if(typeId == 2){
            //课程
            List<Course> courses = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.COURSE_LIST, Course.class);
            if(isRequestList(courses))
                temps.addAll(courses);
        }else if(typeId == 9){
            //全部

            List<Activity> acts = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.ACT_LIST, Activity.class);
            List<Venues> venuess = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.VENUE_LIST, Venues.class);
            List<Course> courses = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.COURSE_LIST, Course.class);

            if(isRequestList(acts)){
                //活动数量
                int actCount = JSONTool.requestJSONfindNameCount(result, JSONTool.Enum.DATA,JSONTool.Enum.ACT_COUNT);
                //Base(int type,int id,String title)
                Base actHeadBase = new Base(1,actCount,QXApplication.getContext().getString(R.string.find_head_act));

                temps.add(actHeadBase);
                temps.addAll(acts);
                if(actCount > ApplicationConfig.FIND_COUNT){
                    Base actFootBase = new Base(2,actCount,QXApplication.getContext().getString(R.string.find_end_act_more));
                    temps.add(actFootBase);
                }
            }

            if(isRequestList(venuess)){
                //场馆数量
                int venueCount = JSONTool.requestJSONfindNameCount(result, JSONTool.Enum.DATA,JSONTool.Enum.VENUE_COUNT);
                //Base(int type,int id,String title)
                Base venueHeadBase = new Base(1,venueCount,QXApplication.getContext().getString(R.string.find_head_venue));

                temps.add(venueHeadBase);
                temps.addAll(venuess);
                if(venueCount > ApplicationConfig.FIND_COUNT){
                    Base venueFootBase = new Base(2,venueCount,QXApplication.getContext().getString(R.string.find_end_venue_more));
                    temps.add(venueFootBase);
                }
            }

            if(isRequestList(courses)){
                //课程数量
                int courseCount = JSONTool.requestJSONfindNameCount(result, JSONTool.Enum.DATA,JSONTool.Enum.COURSE_COUNT);
                //Base(int type,int id,String title)
                Base courseHeadBase = new Base(1,courseCount,QXApplication.getContext().getString(R.string.find_head_course));

                temps.add(courseHeadBase);
                temps.addAll(courses);
                if(courseCount > ApplicationConfig.FIND_COUNT){
                    Base courseFootBase = new Base(2,courseCount,QXApplication.getContext().getString(R.string.find_end_course_more));
                    temps.add(courseFootBase);
                }
            }

        }
        return temps;
    }

    @Event(value = {R.id.quit,R.id.find_edit})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.quit:
            case R.id.find_edit:
                this.finish();
                break;
        }
    }

    @Override
    public void initViewHandler() {
        if(recycler == null)return;
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler.setLayoutManager(layoutVerManager);
    }
}
